//---------------------------------------------------------------------
//  This file is part of the Background Motion solution.
// 
//  Copyright (C) Mindscape (TM).  All rights reserved.
//  http://www.mindscape.co.nz
// 
//  THIS CODE AND INFORMATION ARE PROVIDED AS IS WITHOUT WARRANTY OF ANY
//  KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
//  IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
//  PARTICULAR PURPOSE.
//---------------------------------------------------------------------

using System;
using System.Data.Linq;

namespace Mindscape.BackgroundMotion.Core.Model
{
  public sealed class DLinqUnitOfWorkFactory : IUnitOfWorkFactory
  {
    private readonly string _connectionString;

    private const string ContextKey = "DLinqUnitOfWorkFactory";

    private readonly bool _logSql;

    /// <summary>
    /// Initializes a new instance of the <see cref="DLinqUnitOfWorkFactory"/> class.
    /// </summary>
    /// <param name="connectionString">The connection string.</param>
    public DLinqUnitOfWorkFactory(string connectionString)
      : this(connectionString, false)
    {
    }

    /// <summary>
    /// Initializes a new instance of the <see cref="DLinqUnitOfWorkFactory"/> class.
    /// </summary>
    /// <param name="connectionString">The connection string.</param>
    /// <param name="logSql">if set to <c>true</c> [log SQL].</param>
    public DLinqUnitOfWorkFactory(string connectionString, bool logSql)
    {
      _connectionString = connectionString;
      _logSql = logSql;
    }

    /// <summary>
    /// Creates a new unit of work
    /// </summary>
    /// <returns></returns>
    public IUnitOfWork Create()
    {
      DataContext dataContext = ContextItemsBroker.GetItem<DataContext>(ContextKey);

      if (dataContext == null)
      {
        dataContext = new DataContext(_connectionString);

        if (_logSql)
        {
          dataContext.Log = Console.Out;
        }

        ContextItemsBroker.SetItem(ContextKey, dataContext);
      }

      return new DLinqUnitOfWork(dataContext);
    }
  }
}